package com.example.demo.config;

import com.example.demo.pojo.PlcData;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class PlcDataWebSocketHandler extends TextWebSocketHandler {
    private final Map<String,WebSocketSession> sessions = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper=new ObjectMapper();
    //发送数据
    public void sendPlcDataToAll(PlcData plcData){
        try {
            String json = objectMapper.writeValueAsString(plcData);
            TextMessage message=new TextMessage(json);
            for (WebSocketSession session : sessions.values()) {
                if (session.isOpen()){
                    session.sendMessage(message);
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.put(session.getId(), session);
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session.getId());
    }
}
